package lesson02.UDP;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPEchoClient01 {
    private DatagramSocket socket;
    private String severIp;
    private int severPort;

    public UDPEchoClient01(String severIp, int severPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.severIp = severIp;
        this.severPort = severPort;
    }

    public void start() throws IOException {
        System.out.println("客户端启动.");

        while (true) {
            System.out.println("->");
            Scanner scanner = new Scanner(System.in);
            String request = scanner.nextLine();
            if (request == null || request.isEmpty()) {
                System.out.println("输入数据不能为空");
                continue;
            }

            SocketAddress address = new InetSocketAddress(severIp, severPort);
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    0,request.getBytes().length,address);
            socket.send(requestPacket);

            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),
                    0,responsePacket.getLength(),"UTF-8");
            System.out.printf("requset = %s , response = %s\n",request,response);
        }
    }


    public static void main(String[] args) throws IOException {
        UDPEchoClient01 udpEchoClient = new UDPEchoClient01("127.0.0.1", 9999);
        udpEchoClient.start();
    }
}
